package net.bat.cms;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import net.bat.dao.UserDAO;
import net.bat.entity.Article;
import net.bat.entity.Attach;
import net.bat.entity.IdEntity;
import net.bat.entity.Tag;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
 
@Service
public class CMSService {
	@Autowired
	private UserDAO dao;
	@Autowired
	ServletContext servletContext;

	public static final String splitSec = ";";
	public static final String EN_ARTICLE = "Article";
	public static final String EN_ATTACH = "Attach";
	static final String TPL_DEFAULT = "default";
	private HashMap<String, String> secTpl = null;

	public String[] getSecArticleTpl(String secPathes) {
		// 未选择栏目，直接用默认模版

		if ((secTpl == null) || true) {
			secTpl = new HashMap<String, String>();
			ObjectMapper mapper = new ObjectMapper();
			try {
				String fpath = servletContext.getRealPath("/static/json/sec.json");
				SecNode[] secs = mapper.readValue(new File(fpath), SecNode[].class);

				for (SecNode sn : secs) {
					sn.buildMap(null, sn.getTpl(), secTpl);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		String[] sps = secPathes.split(splitSec);
		String[] result = new String[sps.length];

		for (int i = 0; i < sps.length; i++) {
			result[i] = secTpl.get(sps[i]);
		}
		return result;
	}

	public Article getArticle(long id) {
		return dao.find(Article.class, id);
	}

	public List<Attach> getArticleAttachs(long id) {
		return dao.queryByWhere(Attach.class, " ename='ARTICLE' and eid=? order by o.ord", new Object[] { (int) id });
	}

	// 通过分析sec.json,将栏目映射为uri, 实现下列函数
	// 获得文章的发布到所有频道的uri集合
	public String[] getArticleURI(Article obj) {
		return getArticleURI(obj, obj.getPostto());
	}

	public String[] getArticleURI(long id) {
		Article obj = dao.find(Article.class, id);
		return getArticleURI(obj, obj.getPostto());
	}

	// 获取文章发布到指定栏目的uri
	public String[] getArticleURI(Article obj, String section) {
		if (section == null) {
			return new String[] { CMSController.PATH_ARTICLE + obj.getId() };
		}
		String[] tpl = getSecArticleTpl(obj.getPostto());
		String[] result = new String[tpl.length];

		for (int i = 0; i < result.length; i++) {
			if (tpl[i] == null) {
				result[i] = CMSController.PATH_ARTICLE + obj.getId();
			} else {
				result[i] = CMSController.PATH_ARTICLE + obj.getId() + "_" + tpl[i];
			}
		}
		return result;
	}

	// 专题uri采用 /feature/f1/xxx 形式指定，其中f1表示使用 /tpl/feature/f1.jsp 模版，xxx代表文章id

	private void updateTags(String tags) {
		if (tags == null) {
			return;
		}
		String[] tag_array = tags.split(splitSec);
		for (String element : tag_array) {
			if (dao.isExistedByWhere(Tag.class, "name=?", new Object[] { element })) {
				continue;
			}
			Tag t = new Tag();
			t.setName(element);
			dao.savel(t, null);
		}
	}

	public <T extends IdEntity> T updateAttach(Long id, Map<String, Object> rmap) throws Exception {
		updateTags((String) rmap.get("tag"));
		rmap.put("dtCreate", new Date());
		return dao.update(EN_ATTACH, id, rmap);
	}

	public <T extends IdEntity> T updateArticle(Long id, Map<String, Object> rmap) throws Exception {
		updateTags((String) rmap.get("tag"));
		rmap.put("dtCreate", new Date());
		return dao.update(EN_ARTICLE, id, rmap);
	}

	public <T extends IdEntity> T updateArticle(Map<String, Object> rmap) throws Exception {
		updateTags((String) rmap.get("tag"));
		Long id;
		try {
			id = Long.parseLong(rmap.get("id").toString());
		} catch (Exception e) {
			id = null;
		}
		rmap.put("dtCreate", new Date());
		if (id == null) {
			return addEntity(EN_ARTICLE, rmap);
		} else {
			return dao.update(EN_ARTICLE, id, rmap);
		}
	}

	public <T extends IdEntity> T addEntity(String entity_name, Map<String, Object> rmap) throws Exception {
		return dao.add(entity_name, rmap);
	}

}
